{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "import time\n",
    "import cv2\n",
    "import requests\n",
    "import json\n",
    "import grpc\n",
    "import numpy as np\n",
    "import tensorflow as tf\n",
    "from models.data_prepare import load_and_preprocess_image_pridict\n",
    "from models.config import TABLE_PATH, TEST_PATH, OUTPUT_SHAPE\n",
    "\n",
    "from concurrent import futures\n",
    "from tensorflow_serving.apis import predict_pb2\n",
    "from tensorflow_serving.apis import prediction_service_pb2_grpc"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 配置信息"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "/root/python_project/crnn_by_tensorflow2.2.0/dataset/table.txt\n"
     ]
    }
   ],
   "source": [
    "print (TABLE_PATH)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "#字典\n",
    "with open(TABLE_PATH, 'r',encoding='utf8') as f:\n",
    "    inv_table = [char.strip() for char in f]+[' ']*2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "#测试数据集\n",
    "test_all_image_paths = [TEST_PATH + img for img in sorted(os.listdir(TEST_PATH))]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 调用tensorflow serving方法"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "def text_ocr(image_list):\n",
    "    '''\n",
    "    矩形框文字识别\n",
    "    '''\n",
    "    result_list = []\n",
    "    input_image = []\n",
    "    max_length = max([int(32*img.shape[1]/img.shape[0]) for img in image_list])\n",
    "    for img in image_list:\n",
    "        image = cv2.resize(img, (int(32*img.shape[1]/img.shape[0]), 32), 3)\n",
    "        image = image.astype('float32')\n",
    "        image /= 255\n",
    "        image -= 0.5\n",
    "        image /= 0.5\n",
    "        padding_im = np.zeros((32, max_length, 3), dtype=np.float32)\n",
    "        padding_im[:, 0:image.shape[1],:] = image\n",
    "        input_image.append(padding_im.tolist())\n",
    "    url = 'http://192.168.46.230:7501/v1/models/crnn:predict'\n",
    "    headers = {\"content-type\": \"application/json\"}\n",
    "    data = json.dumps({\n",
    "            \"signature_name\": 'serving_default',\n",
    "            \"instances\":input_image})\n",
    "    start = time.time()\n",
    "    predictions = requests.post(url,data=data, headers=headers,timeout=50).json()\n",
    "    print('识别时间：', time.time()-start)\n",
    "    if 'predictions' in predictions:\n",
    "        if len(predictions['predictions']) > 0:\n",
    "            for sentence in predictions['predictions']:\n",
    "                result = ''\n",
    "                for i in range(len(sentence)):\n",
    "                    char_index = np.argmax(sentence[i])\n",
    "                    if char_index != len(inv_table):\n",
    "                        result +=  inv_table[char_index]\n",
    "                result_list.append(result)\n",
    "    return result_list"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## gRPC调用方法"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "def text_ocr_grpc(image_list):\n",
    "    '''\n",
    "    矩形框文字识别\n",
    "    '''\n",
    "    result_list = []\n",
    "    #grpc配置\n",
    "    \n",
    "    options = [('grpc.max_send_message_length', 1000 * 1024 * 1024), \n",
    "               ('grpc.max_receive_message_length', 1000 * 1024 * 1024)]\n",
    "    channel = grpc.insecure_channel('192.168.46.230:7500', options = options)\n",
    "    stub = prediction_service_pb2_grpc.PredictionServiceStub(channel)\n",
    "    request = predict_pb2.PredictRequest()\n",
    "    request.model_spec.name = 'crnn'\n",
    "    request.model_spec.signature_name = 'serving_default'\n",
    "    #循环遍历每个图片\n",
    "    for img in image_list:\n",
    "        image = cv2.resize(img, (int(32*img.shape[1]/img.shape[0]), 32), 3)\n",
    "        image = image.astype('float32')\n",
    "        image /= 255\n",
    "        image -= 0.5\n",
    "        image /= 0.5\n",
    "        padding_im = np.expand_dims(image, axis=0)\n",
    "        request.inputs['input_1'].CopyFrom(tf.make_tensor_proto(np.asarray(padding_im)))\n",
    "        response = stub.Predict(request, 10.0)\n",
    "        predictions = tf.make_ndarray(response.outputs[\"output_1\"])\n",
    "        for sentence in predictions:\n",
    "            result = ''\n",
    "            for i in range(len(sentence)):\n",
    "                char_index = np.argmax(sentence[i])\n",
    "                if char_index != len(inv_table):\n",
    "                    result +=  inv_table[char_index]\n",
    "            result_list.append(result)\n",
    "    channel.close()\n",
    "    return result_list"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 准备图片"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "image_list = []\n",
    "for i in range(1,111):\n",
    "    image_list.append(cv2.imread(test_all_image_paths[i]))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 调用接口"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "识别时间： 6.148453712463379\n",
      "识别结果： ['番禺检验', '血脂4项(LIP4)(番禺)', '1.16', '1.19', '(PY.Anti-HBe.)', '阴性:>-！阳性:<1', 'PY.乙肝病病毒核心抗体定量', '0.010', '(PY.Anti-HBe.)', ' 结   肝病毒核心抗体定量检查阳性乙肝病毒表 抗体定量检查阳性', '性别:男', '年龄 38', '第5页/共9页', '1..42', '低密度脂蛋白胆固醇(LDL-C)', '2.86', 'mmol//L', '1.50', '3.37', ' 结  油三酯 TG))升  PY 总胆固醇(PY.CHOL))升 ', '前列腺抗原两项(番禺))', '检查日期:2019-12-30', '检查 期 2019-12-28', '项目名称', '检查结果', '参考考值', 'pY.总前列腺特异性抗原', '1.56', 'ng/ml', '(PY..TPSAA', '<4', 'pY游离前列腺特异性抗原', '0..523', '项目名 ', 'ng/ml', '((PY.FPSA)', 'PY 游离PSA//总', '0.34', 'PSA(PY. PSA-Ratio', '>25%BPH风险高', '<<25%前列腺CA风', '险高', '小结:未见明显显异常', '肾功5项(S5)(番禺)', '检查医生 杨玉娟', '检查 期:2019-12-28', '检查医生:杨玉娟', '项目名称', '检查结果', '单位', '提示', '参考值', 'PY.尿酸(PY.UA)', '556', 'umol//1', '检查结 ', '升高', '90', '420', '尿素.(PY.UUREA))', '4.2', 'mmmol/1', '2.86', '8.2', '肌酐.(PY.CREA)', '900.00', '高密度脂蛋白胆固醇(HDDL--C)', 'umol//1', '62', '1115', '白蛋白(ALB)', '41.0', 'g L', '胱抑素素C(CysC)', '0.85', 'mg/L', '0..59', '参考值', '1..03', '小结:PY尿酸((PPY.UA))升高', '乙肝两对半定量((番禺)', '检查 期 2019-12-30', '检查医生:迟琼', '项目名称', '检查结果', '单位', '提示', '参考值', '1.32', 'PY.乙肝病毒表面抗原定量', '<0.050', 'IU/ml', '0.05', '(PY.HBsAg.)', 'PPY.乙肝病毒表面抗体定量', '49.85', 'mIU/m', '0', '10', 'mmol/L', '(PY.Anti-HBs.)', 'PY.乙肝病毒e抗原定量', '0.085', 'COI', '0', '1', '((PY.HBeAg.)', 'PY.乙肝病毒e抗体定量', 'C01', '阴性:》=1阳性性:<1']\n"
     ]
    }
   ],
   "source": [
    "start = time.time()\n",
    "result = text_ocr_grpc(image_list)\n",
    "print('识别时间：', time.time()-start)\n",
    "print('识别结果：', result)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
